//
//  BSPictureView.m
//  Baisijie
//
//  Created by 王建伟 on 2017/3/24.
//  Copyright © 2017年 RangGuangyu. All rights reserved.
//

#import "BSPictureView.h"
#import "BSImageItem.h"
#import "BSGifItem.h"
#import "UIImage+Extension.h"
#import "BSDownloadImageTool.h"
#import <UIImageView+WebCache.h>
#import "BSBigPictureViewController.h"
#import "BSProgressView.h"

@interface BSPictureView ()

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIImageView *gifView;
@property (weak, nonatomic) IBOutlet UIButton *seeBigBtn;
@property (weak, nonatomic) IBOutlet BSProgressView *progressView;

@end
@implementation BSPictureView

- (void)awakeFromNib {
    [super awakeFromNib];
    self.autoresizingMask = UIViewAutoresizingNone;
    [_imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture)]];
}
- (void)tapGesture {
    [self seeBigBtnClick];
}
- (IBAction)seeBigBtnClick {
    BSBigPictureViewController *vc = [BSBigPictureViewController new];
    vc.gifImage = (_gif != nil);
    vc.image = _image;
    vc.gif = _gif;
    [self.window.rootViewController presentViewController:vc animated:YES completion:nil];
}
- (void)setImage:(BSImageItem *)image {
    _image = image;
    _gifView.hidden = YES;
    CGFloat imageH = self.bs_width * image.height / image.width;
    _seeBigBtn.hidden = (imageH <= KScreenW);
    _progressView.progress = 0.0;
    _progressView.hidden = NO;
    [BSDownloadImageTool bs_showImageInImageView:_imageView bigImageUrl:image.big.firstObject thumbnailImageUrl:image.big.lastObject useTop:!_seeBigBtn.hidden progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        _progressView.progress = receivedSize * 1.0 / expectedSize;
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        _imageView.userInteractionEnabled = image;
        _progressView.hidden = YES;
        _imageView.image = !_seeBigBtn.hidden ? [UIImage bs_showTopImageWithImage:image size:_imageView.bs_size] : image;
    }];
}
- (void)setGif:(BSGifItem *)gif {
    _gif = gif;
    _gifView.hidden = NO;
    _seeBigBtn.hidden = YES;
    _progressView.progress = 0.0;
    _progressView.hidden = NO;
    [_imageView sd_setImageWithURL:[NSURL URLWithString:gif.images.lastObject] placeholderImage:nil options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        _progressView.progress = receivedSize * 1.0 / expectedSize;
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        _imageView.userInteractionEnabled = image;
        _progressView.hidden = YES;
    }];
}

@end
